package com;

import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * Description:前序遍历（非递归）
 * User: YJ
 * Date: 2024-4-21
 * Time: 16:44
 */
public class E01LeetCode144 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,new TreeNode(2,new TreeNode(4),null)
                ,new TreeNode(3,new TreeNode(5),new TreeNode(6)));
        preOrder(root);
    }
    static void preOrder(TreeNode root) {
        LinkedList<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                System.out.println("前序：" + cur.val);
                stack.push(cur); // 入栈，记住来时的路
                cur = cur.left;
            } else {
                TreeNode pop = stack.pop();
                System.err.println("中序" + pop.val);
                cur = pop.right;
            }
        }
    }
}
